import java.util.LinkedList;
import java.util.Queue;

class Solution {

    static int[] dx = {1,-1,0,0};
    static int[] dy = {0,0,-1,1};
    static boolean[][] visited;
    static int m;
    static int n;

    public static int numIslands(char[][] grid) {
        m = grid.length;
        n = grid[0].length;
        visited = new boolean[m][n];
        // 在每一个位置进行一次BFS即可
        int ret = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // 从岛屿开始BFS
                if (grid[i][j] == '1' && !visited[i][j]) {
                    bfs(grid, i, j);
                    ret++;
                }
            }
        }
        return ret;
    }

    private static void bfs(char[][] grid, int i, int j) {
        // 从i,j位置开始BFS
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{i, j});
        visited[i][j] = true; // 设置为访问过
        while (!queue.isEmpty()) {
            int[] arr = queue.poll();
            for (int k = 0; k < 4; k++) {
                int sr = arr[0] + dx[k], sc = arr[1] + dy[k];
                // 确保 不越界、是岛屿、未访问过
                if (sr >= 0 && sr < m && sc >= 0 && sc < n && grid[sr][sc] == '1' && !visited[sr][sc]) {
                    queue.offer(new int[]{sr, sc});
                    visited[sr][sc] = true;
                }
            }
        }
    }


    public static void main(String[] args) {
        char[][] grid = {
                {'1', '1', '1','1','0'},
                {'1', '1', '0','1','0'},
                {'1', '1', '0','0','0'},
                {'0', '0', '0','0','0'}
        };
        System.out.println(numIslands(grid));
    }
}